<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>注册</title>
</head>
<script src="js/http.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<body>
  <p class="bar">
    <label >导航栏</label>
    <span onclick="location.href='login.html'">登录页</span>
    <span onclick="location.href='register.html'">注册页</span>
    <span onclick="location.href='welcome.html'">欢迎页</span>
  </p>
  <form>
    <p><label>邮箱：</label><input name="email" onchange="mailChange()"/></p>
    <p><label>密码：</label><input name="password" type="password" /></p>
    <p><label>确认密码：</label><input name="confirmPassword" type="password" /></p>
    <p><label>验证码：</label><input name="code"  /></p>
    <p>
      <span class="btn" onclick="getCode()" id="code-btn">获取验证码</span>
    </p>
    <p>
      <span class="btn" onclick="register()">注册</span>
    </p>
  </form>
  
</body>
<script>
function mailChange(){
  let email = $('input[name="email"]')[0].value
  if(emailValidator(email)){
    ajax(`/api/user/isRegistered/${email}`,(res)=>{
      if(res === true || res === 'true'){
        alert('当前用户已注册！')
      }
    },(res)=>{
      if(res === true || res === 'true'){
        alert('当前用户已注册！')
      }
    })
  }
}
function register(){
  let email = $('input[name="email"]')[0].value
  let password = $('input[name="password"]')[0].value
  let code = $('input[name="code"]')[0].value
  let confirmPassword = $('input[name="confirmPassword"]')[0].value
  if(!emailValidator(email)){
    alert('请输入正确的邮箱！')
    return
  }
  if(password === ''){
    alert('密码不能为空！')
    return
  }
  if(password !== confirmPassword){
    alert('两次密码不一致！')
    return
  }
  ajax(`/api/user/register/${email}/${password}/${code}`,(res)=>{
    alert(res)
  },(res)=>{
    alert(res)
  })
}
function getCode(){
  let email = $('input[name="email"]')[0].value
  let dom = document.getElementById('code-btn')
  if(dom.innerHTML !== '获取验证码'){
    return
  }
  if(!emailValidator(email)){
    alert('请输入正确的邮箱！')
    return
  }
  lockBtn('code-btn')
  ajax(`/api/code/create/${email}`,(res)=>{
    if(res === true || res === 'true'){
      alert('验证码发送成功！')
    }else{
      alert('发送失败！')
    }
  },(res)=>{
    if(res === true || res === 'true'){
      alert('验证码发送成功！')
    }else{
      alert('发送失败！')
    }
  })
}
function emailValidator(value){
  let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
  return reg.test(value)
}
function lockBtn(id){
  let dom = document.getElementById(id)
  dom.innerHTML = '60'
  let timer = setInterval(()=>{
    let value = parseInt(dom.innerHTML)
    dom.innerHTML = value - 1
    if(value <=0){
      clearInterval(timer)
      dom.innerHTML = '获取验证码'
    }
  },1000)
}
</script>
</html>